import gradio as gr
from datetime import datetime
from tools.search_registry import search_papers

SEARCH_FIELDS = {
    'europepmc': ['title', 'author', 'container_title', 'rows', 'download_pdf', 'save_dir'],
    'arxiv': ['keywords', 'title', 'author', 'abstract', 'include_cat', 'exclude_cat', 'comment', 'start_date', 'end_date', 'max_results', 'download_pdf', 'save_dir'],
    'springer': ['keywords', 'title', 'author', 'abstract', 'max_results', 'download_pdf', 'save_dir'],
}

def search_gui(
    keywords, title, author, abstract, include_cat, exclude_cat,
    comment, start_date, end_date, max_results, download_pdf, save_dir, source, email,
    container_title, rows
):
    if source == 'europepmc' and not (title or author or container_title):
        return "Europe PMC 检索至少需要填写标题、作者或期刊名称之一。"
    if source == 'springer' and not (keywords or title or author or abstract):
        return "Springer 检索至少需要填写关键词、标题、作者或摘要之一。"
    if source == 'europepmc':
        kwargs = {
            'title': title or None,
            'author': author or None,
            'container_title': container_title or None,
            'rows': rows or 3,
            'download_pdf': download_pdf,
            'save_dir': save_dir or './papers',
        }
    elif source == 'springer':
        kwargs = {
            'keywords': keywords or None,
            'title': title or None,
            'author': author or None,
            'abstract': abstract or None,
            'max_results': max_results,
            'download_pdf': download_pdf,
            'save_dir': save_dir or './papers',
        }
    else:
        kwargs = {
            'keywords': keywords or None,
            'title': title or None,
            'author': author or None,
            'abstract': abstract or None,
            'include_cat': include_cat or None,
            'exclude_cat': exclude_cat or None,
            'comment': comment or None,
            'max_results': max_results,
            'download_pdf': download_pdf,
            'save_dir': save_dir or './papers',
        }
        if start_date:
            try:
                kwargs['start_date'] = datetime.strptime(start_date, "%Y-%m-%d")
            except Exception:
                return "起始时间格式错误，应为 yyyy-mm-dd"
        if end_date:
            try:
                kwargs['end_date'] = datetime.strptime(end_date, "%Y-%m-%d")
            except Exception:
                return "截止时间格式错误，应为 yyyy-mm-dd"
    try:
        results = search_papers(source, **kwargs)
    except Exception as e:
        return f"搜索出错: {e}"
    if not results:
        return "未找到符合条件的论文。"
    out = []
    for r in results:
        if source == 'europepmc':
            out.append(f"""📌 标题: {r.get('title','')}
📰 期刊: {r.get('journalTitle','')}
👨‍🔬 作者: {r.get('authors','')}
📅 发表日期: {r.get('published','')}
🔗 PDF链接: {r.get('pdf_url') or '无'}
🔗 Resource链接: {r.get('resource_url') or '无'}
""")
        elif source == 'arxiv':
            out.append(f"""📌 标题: {r['title']}\n👨‍🔬 作者: {', '.join(r['authors'])}\n📅 提交时间: {r['published'].strftime('%Y-%m-%d')}\n🗂 分类: {r['primary_category']}\n📝 摘要: {r['summary'][:500]}...\n🔗 链接: {r['pdf_url']}\n""")
        elif source == 'springer':
            out.append(f"""📌 标题: {r.get('title','')}\n👨‍🔬 作者: {r.get('authors','')}\n🗂 分类: {r.get('primary_category','')}\n📝 摘要: {r.get('summary','')[:500]}...\n🏢 出版社: {r.get('publisherName','')}\n📅 出版日期: {r.get('publicationDate','')}\n🔗 PDF链接: {r.get('pdf_url') or '无'}\n""")
    return "\n\n <============================> \n\n".join(out)

with gr.Blocks(title="论文搜索客户端") as demo:
    gr.HTML("""
    <style>
    body, .gr-block, .gr-form, .gr-box, .gr-input, .gr-textbox label, .gr-textbox input, .gr-textbox textarea, .gr-button, .gr-slider label, .gr-slider input, .gr-dropdown label, .gr-dropdown input {
        font-size: 20px !important;
    }
    #output-box textarea {
        font-size: 22px !important;
        line-height: 1.6;
    }
    </style>
    """)
    gr.Markdown("# 论文搜索工具 (Europe PMC / Springer / arXiv)")
    with gr.Row():
        source = gr.Dropdown(label="搜索源", choices=["europepmc", "springer", "arxiv"], value="europepmc")
        email = gr.Textbox(label="（已隐藏）", visible=False)
    with gr.Row():
        keywords = gr.Textbox(label="关键词", placeholder="large language model", visible=False)
        title = gr.Textbox(label="标题关键词 (ti)", visible=True)
        author = gr.Textbox(label="作者名 (au)", visible=True)
    with gr.Row():
        container_title = gr.Textbox(label="期刊名称 (Europe PMC)", visible=True)
        abstract = gr.Textbox(label="摘要关键词 (abs)", visible=False)
        include_cat = gr.Textbox(label="包含分类 (cat)", placeholder="cs.CL", visible=False)
    with gr.Row():
        exclude_cat = gr.Textbox(label="排除分类 (cat)", placeholder="math.OC", visible=False)
        comment = gr.Textbox(label="作者评论 (co)", placeholder="ICLR 2023", visible=False)
        start_date = gr.Textbox(label="起始时间 (yyyy-mm-dd)", visible=False)
    with gr.Row():
        end_date = gr.Textbox(label="截止时间 (yyyy-mm-dd)", visible=False)
        max_results = gr.Slider(label="最大返回数量", minimum=1, maximum=50, value=5, step=1, visible=False)
        rows = gr.Slider(label="Europe PMC条数(rows)", minimum=1, maximum=10, value=3, step=1, visible=True)
    with gr.Row():
        download_pdf = gr.Checkbox(label="是否下载 PDF", value=False, visible=True)
        save_dir = gr.Textbox(label="保存路径", value="./papers", visible=True)
    output = gr.Textbox(label="搜索结果", lines=5, elem_id="output-box")
    btn = gr.Button("搜索")

    def update_fields(src):
        fields = SEARCH_FIELDS[src]
        return [
            gr.update(visible='keywords' in fields or 'term' in fields),
            gr.update(visible='title' in fields),
            gr.update(visible='author' in fields),
            gr.update(visible='container_title' in fields),
            gr.update(visible='abstract' in fields),
            gr.update(visible='include_cat' in fields),
            gr.update(visible='exclude_cat' in fields),
            gr.update(visible='comment' in fields),
            gr.update(visible='start_date' in fields),
            gr.update(visible='end_date' in fields),
            gr.update(visible='max_results' in fields),
            gr.update(visible='rows' in fields),
            gr.update(visible='download_pdf' in fields),
            gr.update(visible='save_dir' in fields),
            gr.update(visible=False),
        ]
    source.change(
        update_fields,
        inputs=source,
        outputs=[keywords, title, author, container_title, abstract, include_cat, exclude_cat, comment, start_date, end_date, max_results, rows, download_pdf, save_dir, email]
    )

    btn.click(fn=search_gui,
              inputs=[keywords, title, author, abstract,
                      include_cat, exclude_cat, comment,
                      start_date, end_date, max_results, download_pdf, save_dir, source, email,
                      container_title, rows],
              outputs=output)

demo.launch()